package com.hyy.trigger.service;

import com.hyy.trigger.action.*;
import com.hyy.trigger.machine.ActionSource;
import com.hyy.trigger.machine.Basket;
import com.hyy.trigger.machine.RuleMachine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.squirrelframework.foundation.fsm.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.hyy.trigger.machine.State.*;
import static com.hyy.trigger.util.TriggerUtil.event;
import static com.hyy.trigger.util.TriggerUtil.getLines;


/**
 * Created by Satroler on 2017/9/4.
 */
public class StatusMachineActionServiceWithSquirrel {

    Logger logger = LoggerFactory.getLogger(getClass());

    UntypedStateMachineBuilder builder;


    public void initBuilder (){
        builder = StateMachineBuilderFactory.create(RuleMachine.class);
        //1、进行数据清洗
        //2、执行语气处理
        //3、如果是拒绝，直接返回
        //4、执行名字处理
        //5、执行地理位置处理
        //6、执行年龄处理
        //7、执行品牌信息

        List<UntypedAnonymousAction> actions = Arrays.asList(new ClearAction(),new MoodAction(),new DenyAction(),
                new NameAction(),new LocationAction(),new AgeAction(),new BrandAction());
        List<String> lines = getLines();
        external(INIT,lines.get(0));
        for (int i = 0; i < lines.size(); i++) {
            String cur = lines.get(i);
            if(i!=lines.size()-1){
                external(cur,lines.get(i+1));
                onEntry(cur,actions.get(i));
                call(cur);
            }
            external(cur,END);
        }
    }

    private void external(String from, String to){
        builder.externalTransition().from(from).to(to).on(event(from, to));
    }

    private void onEntry(String entry, Action action){
        builder.onEntry(entry).perform(action);
    }

    private void call(String entry){
        builder.onEntry(entry).callMethod("onEntry");
    }

    public Map getActionResult(ActionSource actionSource){

        UntypedStateMachine fsm = builder.newStateMachine(INIT);
        Basket basket = new Basket();
        basket.setActionSource(actionSource);
        basket.setLines(getLines());
        fsm.fire(event(INIT,CLEAR),basket);
        Map res = basket.getResultData();
        System.out.println("+++++++++++++++++++++++++++++++++++++"+fsm.getCurrentState());
        return res;

    }


    public static void main(String[] args) {
        StatusMachineActionServiceWithSquirrel squirrel = new StatusMachineActionServiceWithSquirrel();
        squirrel.initBuilder();
        for (int i = 0; i < 1; i++) {
            squirrel.getActionResult(null);
        }

    }


}
